<template>
  <div class="chart" ref="chartDom"></div>
</template>

<script setup lang="ts">
import { onMounted, reactive, ref, toRaw, toRef, watch } from "vue";
import { BarSeriesOption } from "echarts/charts";
import Echarts from "../modules/echarts";
import { useGlobalStore } from "../modules/pinia";
import { ECBasicOption } from "echarts/types/dist/shared";
interface myChartDt {
  instances: Echarts.ECharts | null;
  option: ECBasicOption;
  width: number;
  height: number;
}
const chartDom = ref<HTMLElement | null>(null);
const globalStore = useGlobalStore();
const myChart: myChartDt = reactive({
  instances: null,
  option: {
    title: {
      text: "📕 其他",
      left: 10,
      top: 10,
    },
    xAxis: {
      type: "category",
      data: ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"],
    },
    yAxis: {
      type: "value",
    },
    series: <BarSeriesOption>[
      {
        data: [120, 200, 150, 80, 70, 110, 130],
        type: "bar",
        showBackground: true,
        backgroundStyle: {
          color: "rgba(180, 180, 180, 0.2)",
        },
      },
    ],
  },
  width: 0,
  height: 0,
});

watch(
  [
    () => globalStore.isReady,
    () => globalStore.theme,
    () => myChart.width,
    () => myChart.height,
  ],
  () => {
    initChart();
    updateChart();
    const observer = new ResizeObserver(resizeChart);
    observer.observe(chartDom.value as HTMLElement);
  }
);

onMounted(() => {
  window.addEventListener("resize", resizeChart);
  initChart();
});

function initChart() {
  if (myChart.instances) myChart.instances!.dispose();
  myChart.instances = Echarts.init(
    chartDom.value as HTMLElement,
    globalStore.theme
  );
}

function updateChart() {
  const { instances, option } = toRaw(myChart);
  instances!.setOption(option);
}

function resizeChart() {
  myChart.instances!.resize();
}
</script>

<style scoped></style>
